package edu.uestc.canary.service.bean;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.uestc.canary.commons.EncryptUtils;
import edu.uestc.canary.commons.JWTUtils;
import edu.uestc.canary.commons.StringUtils;
import edu.uestc.canary.entity.dto.Result;
import edu.uestc.canary.entity.pojo.Administrator;
import edu.uestc.canary.repository.mapper.AdministratorMapper;
import edu.uestc.canary.service.AdministratorService;
import jakarta.annotation.Resource;
import org.springframework.boot.jackson.JsonObjectSerializer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdministratorServiceBean implements AdministratorService {
    @Resource private AdministratorMapper mapper;
    @Resource private StringRedisTemplate stringTemplate;

    @Override
    public Result login(String username, String password) {
        //根据用户名查找管理员
        var wrapper = new LambdaQueryWrapper<Administrator>()
                .eq(Administrator::getUsername, username); //设置查询条件  where username = ?
        var administrator = mapper.selectOne(wrapper);
        if(administrator != null && EncryptUtils.bcryptCheck(password,administrator.getPassword())) {
            //生成jwt且将jwt保存进redis
            var jwt = JWTUtils.compact(Map.of("id",administrator.getId()));
            var value = JSONObject.toJSONString(administrator);
            stringTemplate.opsForValue().set("canary:token:" + jwt, value, 30, TimeUnit.MINUTES);
            return Result.ok(jwt);
        }
        return Result.fail(null,"登录失败:用户名或密码错误");
    }

    @Override
    public Result loginByPhone(String phone, String code) {
        //根据手机号码查找管理员信息
        var wrapper = new LambdaQueryWrapper<Administrator>()
                .eq(Administrator::getPhone, phone);
        var administrator = mapper.selectOne(wrapper);
        if(administrator != null){
            var code1 = stringTemplate.opsForValue().get("canary:code:" + phone);
            if(code.equals(code1)) {
                //生成jwt且将jwt保存进redis
                var jwt = JWTUtils.compact(Map.of("id", administrator.getId()));
                var value = JSONObject.toJSONString(administrator);
                stringTemplate.opsForValue().set("canary:token:" + jwt, value, 30, TimeUnit.MINUTES);
                return Result.ok(jwt);
            }
            return Result.fail(null,"登录失败:验证码错误");
        }
        return Result.fail(null,"登录失败:该手机号未注册");
    }

    @Override
    public Result sendVerificationCode(String phone) {
        //1.生成验证码
        String code = StringUtils.genericCode(6);
        //2.发送验证码给手机号(参考阿里云-短信服务)

        //3.保存验证码
        stringTemplate.opsForValue().set("canary:code:" + phone, code, 5, TimeUnit.MINUTES);
        return Result.ok(code); //将验证码返回给前端
    }
}
